#include <iostream>
#include <string.h>
using namespace std;
//当字符串长度大于15时，buffer中存放的是指针，当字符串长度小于等于15时，存放的是字符串
class String {
public:
    String(const char * pstr){
        int _size=strlen(pstr);
        if(_size>15){
            flag=0;
        _buffer._pointer=new char(15);
        strcpy(_buffer._pointer,pstr);
        }else{
            flag=1;
            strcpy(_buffer._local,pstr);
            _capacity=15-_size;
        }
    }
    ~String(){
        if(flag==0){
            delete _buffer._pointer;
            _buffer._local[15]={0};
        }else{
        _buffer._local[15]={0};
    }
    }
    char &  operator[](size_t idx){
        if(idx>_size){
            static
            char ch='/0';
            return ch;
        }
        if(flag==0){
            return _buffer._pointer[idx];
        }else{
            return _buffer._local[idx];
        }
    }
    friend
        ostream & operator<<(ostream & os,const String & rhs);
private:

    union Buffer{
		char * _pointer;
		char _local[16];
	};
    bool flag;
	size_t _size;//占8个字节
    size_t _capacity;//占8个字节
    Buffer _buffer;//占16个字节
};

ostream & operator<<(ostream & os,const String & rhs){
    if(rhs.flag==0){
    cout<<rhs._buffer._pointer;
    }else{
        cout<<rhs._buffer._local;
    }
    return os;
}
void test0(){
    String str1("hello");
    String str2("hello,world!!!!!");
    String str3("world");

    cout<<str1[1]<<endl;
    cout<<str2[1]<<endl;
    
    cout<<str1<<endl;
    cout<<str2<<endl;
}
int main(){
    test0();
    return 0;
}
 
